<template>
  <h1>登录页面</h1>
  <el-input placeholder="请输入用户名" v-model="query.username"></el-input>
  <el-input placeholder="请输入密码" v-model="query.password"></el-input>
  <el-button type="primary" @click="login">登录</el-button>
  <router-link to="/register">注册</router-link>
</template>

<script setup>
import {ref} from 'vue'
import router from "@/router/index.js"
import axios from "axios"
import {ElMessage} from "element-plus"

const query = ref({
  username: '',
  password: ''
})

const login = () => {
  if (query.value.username === '' || query.value.password === '') {
    ElMessage.error('用户名或密码不能为空')
    return
  }

  axios.post('http://localhost:8000/app/access_token/', query.value, {
    headers: {
      'Content-Type': 'application/json'
    }
  })
      .then(res => {
        console.log(res.data)
        if (res.data && res.data.access) {
          localStorage.setItem('token', res.data.access)
          localStorage.setItem('refresh', res.data.refresh)
          query.value.username = ''
          query.value.password = ''
          router.push('/')
          ElMessage.success('登录成功')
        } else {
          ElMessage.error('服务器返回数据异常')
        }
      })
      .catch(err => {
        ElMessage.error('请求失败，请稍后再试')
      })
}
</script>
